using GameFramework;
using GameFramework.Resource;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace StarForce
{
    public class Prop : Entity
    {
        [SerializeField] private PropData m_PropData = null;

        private SpriteRenderer m_SpriteRenderer;
        
        private LoadAssetCallbacks m_LoadAssetCallbacks;
        
        
        protected override void OnInit(object userData)
        {
            base.OnInit(userData);

            m_LoadAssetCallbacks = new LoadAssetCallbacks(OnLoadAssetSuccess, OnLoadAssetFailure);

            m_SpriteRenderer = gameObject.GetOrAddComponent<SpriteRenderer>();
            m_SpriteRenderer.enabled = false;
        }
        protected override void OnShow(object userData)
        {
            base.OnShow(userData);
            m_PropData = userData as PropData;
            if (m_PropData == null)
            {
                Log.Error("Player object data is invalid.");
                return;
            }

            CachedTransform.localPosition = m_PropData.Location;
            GameEntry.Resource.LoadAsset( GameUtility.GetPropImageByType(m_PropData.PropType), typeof(Sprite),
                Constant.AssetPriority.GroundAssets, m_LoadAssetCallbacks, this);
           
        }

        private void OnTriggerEnter2D(Collider2D other)
        {
            GameEntry.Entity.HideEntity(this);
        }

        protected override void OnHide(bool isShutdown, object userData)
        {
            base.OnHide(isShutdown, userData);
            GameEntry.Event.Fire(this,ReferencePool.Acquire<PropEventArgs>().Fill(m_PropData.PropType));
        }

        private void OnLoadAssetFailure(string assetname, LoadResourceStatus status, string errormessage,
            object userdata)
        {
            Log.Error(Utility.Text.Format("Error in '{0}',LoadresoureceStatus:{1},Error Message:{2}", assetname,
                status, errormessage));
        }

        private void OnLoadAssetSuccess(string assetname, object asset, float duration, object userdata)
        {
            if (!ReferenceEquals(this, userdata))
            {
                return;
            }

            if (asset == null)
            {
                Log.Error("Asset is invalid.");
                return;
            }

            if (m_SpriteRenderer == null)
            {
                Log.Error("Renderer is invalid.");
                return;
            }

            m_SpriteRenderer.sprite = (Sprite) asset;
            m_SpriteRenderer.enabled = true;
        }
        
    }
}